package com.xbongbong.parent.field.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.parent.field.FieldAnalyseService;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.FilterConditionsPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.businessrule.pojo.BusinessRuleInfoPojo;
import com.xbongbong.parent.util.LinkDataUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/07/07 14:25
 */
@Service("linkBusinessSingleFieldAnalyseServiceImpl")
public class LinkBusinessSingleFieldAnalyseServiceImpl implements FieldAnalyseService {

    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
    }

    @Override
    public Object analysisData(Long formId, Integer businessType, Integer saasMark, PaasFormDataEntityExt paasFormDataEntityExt, JSONObject data, FieldAttrEntity fieldAttrEntity) throws XbbException {
       return data.get(fieldAttrEntity.getLinkedText());
    }

    @Override
    public Object handlerPreConditionValue(FieldAttrEntity thisField, BusinessRuleInfoPojo businessRuleInfoPojo, FilterConditionsPoJo filterCondition) throws XbbException {
        if (Objects.equals(ConditionEnum.IN.getSymbol(), filterCondition.getSymbol()) || Objects.equals(ConditionEnum.NOIN.getSymbol(), filterCondition.getSymbol())) {
            if (filterCondition.getValue() instanceof List) {
                List<String> idList = new ArrayList<>();
                // 关联业务单选的格式
                List<Map<String, Object>> linkSingleList = (List) filterCondition.getValue();
                for (int i = 0; i < linkSingleList.size(); i++) {
                    Map<String, Object> linkSingle = linkSingleList.get(i);
                    if (Objects.nonNull(linkSingle) && Objects.nonNull(linkSingle.get("id"))) {
                        idList.add(linkSingle.get("id").toString());
                    }
                }
                return idList;
            }
        }
        return LinkDataUtil.getIdByLinkBusiness(filterCondition.getValue());
    }
}
